{% extends "base.html" %}
{% load i18n %}
{% load static %}
{% block content %}
    <div id="content">

    <!-- Begin Page Content -->
    <div class="container-fluid">

        <!-- Page Heading -->
        <h1 class="h3 mb-2 text-gray-800">资源组管理</h1>

        <!-- 模态框 -->
        <div class="modal fade" id="rgModal" tabindex="-1" role="dialog" aria-labelledby="rgModalLabel" aria-hidden="true">
          <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
              <!-- 模态框头部 -->
              <div class="modal-header">
                <h5 class="modal-title" id="rgModalLabel">资源组管理</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <!-- 模态框主体内容 -->
              <div class="modal-body">
                <form>
                  <div class="form-group d-flex align-items-center">
                    <label for="input1" class="mr-3 w-25"><span class="text-danger">*</span>&nbsp;名称</label>
                    <input type="text" class="form-control w-75" id="input1" placeholder="请输入内容">
                  </div>
                  <div class="form-group d-flex align-items-center">
                    <label for="input2" class="mr-3 w-25"><span class="text-danger">*</span>&nbsp;描述</label>
                    <input type="text" class="form-control w-75" id="input2" placeholder="请输入内容">
                  </div>
                  <div class="form-group d-flex align-items-center" style="display:none">
                    <label class="mr-3" for="aclCheck" style="display:none"><span class="text-danger">*</span> 匹配只读策略</label>
                    <div class="custom-control custom-checkbox ml-3" style="display:none">
                      <input type="checkbox" class="custom-control-input" id="aclCheck" style="display:none">
                      <label class="custom-control-label" for="aclCheck" style="display:none"></label>
                    </div>
                  </div>
                  <!-- 双向选择框 -->
                  <div class="form-group">
                    <div class="row">
                      <div class="col">
                          <label class="mr-5"><span class="text-danger">*</span>&nbsp;可选 Master: </label>
                        <select id="availableOptions" multiple class="form-control" style="height: 200px; background-color: white; color: black; text-align: left; border: 1px solid #ced4da;">
                          {% for each_master in all_masters %}
                            <option value="{{ each_master.id }}">{{ each_master.name }}</option>
                            {% endfor %}
                        </select>
                      </div>
                        <div class="col-1 d-flex flex-column align-items-center justify-content-center">
                          <button type="button" class="btn btn-primary w-100" id="moveRight"><span class="ml-0">→</span></button>
                          <button type="button" class="btn btn-primary w-100 mt-2" id="moveLeft">←</button>
                        </div>
                      <div class="col">
                          <label class="mr-5"><span class="text-danger">*</span>&nbsp;已选 Master: </label>
                        <select id="selectedOptions" multiple class="form-control" style="height: 200px; background-color: white; color: black; text-align: left; border: 1px solid #ced4da;">
                          <!-- 已选择的项会显示在这里 -->
                        </select>
                      </div>
                    </div>
                  </div>

                  <div style="display: none;">
                    <label for="input6" class="mr-3 w-25"></label>
                    <input type="text" class="form-control w-75" id="input6" placeholder="">
                  </div>
                </form>
                  <label class="mr-3 w-100"><span id="msg" class="text-danger"></span></label>
              </div>
              <!-- 模态框底部 -->
              <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="create_rg()">提交</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 确认模态框 -->
        <div class="modal fade" id="confirmModal" tabindex="-1" role="dialog" aria-labelledby="confirmModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <!-- 模态框头部 -->
              <div class="modal-header">
                <h5 class="modal-title" id="confirmModalLabel">确认操作</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <!-- 模态框主体内容 -->
              <div class="modal-body">
                您确定要进行此操作吗？该操作无法撤销
              </div>
              <div class="modal-body">
                <label class="mr-3 w-100"><span id="confirm_msg" class="text-danger"></span></label>
              </div>
              <!-- 模态框底部 -->
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmButton" onclick="del_resource_group()">确认</button>
              </div>
            </div>
          </div>
        </div>
        <!-- DataTales Example -->
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <button id="add_salt" class="btn btn-primary btn-sm mr-2" onclick="clear_rowText()"> &nbsp;添&nbsp;加&nbsp; </button>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                        <thead>
                            <tr>
                                <th>名称</th>
                                <th>描述</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tfoot>
                            <tr>
                                <th>名称</th>
                                <th>描述</th>
                                <th>操作</th>
                            </tr>
                        </tfoot>
                        <tbody>
                            <tr style="display: none;">
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            {% for each_rg in all_rg %}
                            <tr id="tr-{{ each_rg.id }}">
                                <td>{{ each_rg.name }}</td>
                                <td>{{ each_rg.description }}</td>
                                <td style="display: none;">{{ each_rg.id }}</td>
                                <td>
                                    <button type="button" class="btn btn-primary btn-sm" onclick="get_rowText(this)" data-row-id="tr-{{ each_rg.id }}">编辑</button>
                                    <button type="button" class="btn btn-danger btn-sm" onclick="get_rowid(this)" id="{{ each_rg.id }}">删除</button>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>
    <!-- /.container-fluid -->
    <div id="load" class="position-fixed w-100 h-100"
     style="top: 0; left: 0; background: rgba(255, 255, 255, 0.2); z-index: 1100; display: none;
            justify-content: center;
            align-items: center;">
        <div class="spinner-border text-success" role="status" style="width: 3rem; height: 3rem; position: absolute; top: 50%; left: 50%; margin-top: -1.5rem; margin-left: -1.5rem;">
        <span class="sr-only">加载中...</span>
    </div>
    <!-- 引入 Bootstrap 4 和 jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
{% endblock content %}
{% block js %}
    <script type="text/javascript">
          $(document).ready(function() {
            // 移动右侧按钮事件：将选中的项从左侧移动到右侧
            $('#moveRight').click(function() {
              $('#availableOptions option:selected').each(function() {
                $('#selectedOptions').append($(this));  // 将选中的项添加到右侧
              });
            });

            // 移动左侧按钮事件：将选中的项从右侧移动到左侧
            $('#moveLeft').click(function() {
              $('#selectedOptions option:selected').each(function() {
                $('#availableOptions').append($(this));  // 将选中的项添加到左侧
              });
            });
          });

        // 设置加载图片
        function loading() {
            document.getElementById('load').style.display = 'flex';
        };

        // 移除加载图片
        function loading_remove() {
            document.getElementById('load').style.display = 'none';
        };

        // 移除reminder
        function reminder_remove() {
            var reminder_msg = document.getElementById("msg");
            reminder_msg.innerHTML = '';
        };

        //创建salt rg
        function create_rg() {
            reminder_remove()
            var reminder_msg = document.getElementById("msg");
              var selectedValues = [];
              // 遍历所有的 option 元素，提取它们的值
              $('#selectedOptions option').each(function() {
                selectedValues.push($(this).val());
              });
            $.ajax({
                type: "post",
                url: "/create_resource_group/",
                dataType: "json",
                data: {
                    input1: $("#input1").val(),
                    input2: $("#input2").val(),
                    input6: $("#input6").val(),
                    aclcheck: $("#aclCheck").prop('checked'),
                    selectedValues: selectedValues,
                },
                complete: function () {
                },
                success: function (data) {
                    if (data.status === 0) {
                        reminder_msg.innerHTML = 'Reminder: ' + data.msg;
                        $('#rgModal').modal('hide');
                        location.reload();
                    } else {

                        reminder_msg.innerHTML = 'Reminder: ' + data.msg;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reminder_msg.innerHTML = 'Reminder: ' + errorThrown;
                }
            });
        }

        // 点击删除按钮时设置确认按钮的
        function get_rowid(button) {
                reminder_remove();
                // 设置确认按钮的 data-id 属性
                document.querySelector('#confirmButton').setAttribute('data-id', button.id);

                // 显示确认框
                $('#confirmModal').modal('show');
        }

       // 定义一个函数来处理填充 selectedOptions
        function populateSelectedOptions(data, id) {
            const selectedValues = data[id] || [];

            // 获取 selectedOptions and availableOptions 元素
            const selectedOptionsElement = document.getElementById('selectedOptions');
            const availableOptionsElement = document.getElementById('availableOptions');

            // 清空现有的选项
            selectedOptionsElement.innerHTML = '';

            // 填充 selectedOptions
            for (const [id, name] of Object.entries(selectedValues)) {
                const optionElement = document.createElement('option');
                optionElement.value = id;
                optionElement.textContent = name;  // 使用字典中的 name 作为选项文本

                selectedOptionsElement.appendChild(optionElement);
                availableOptionsElement.querySelector(`option[value="${id}"]`).remove();
            }
        }

        // 重新填充所有内容
        function refullText() {
            const allValues = {{ all_masters_dic|safe }};
            const initAvailableOptionsElement = document.getElementById('availableOptions');
            initAvailableOptionsElement.innerHTML = '';  // 清空选项
            for (const [id, name] of Object.entries(allValues["amd"])) {
                const optionElement = document.createElement('option');
                optionElement.value = id;
                optionElement.textContent = name;  // 使用字典中的 name 作为选项文本

                initAvailableOptionsElement.appendChild(optionElement);
            }
        }

        // 编辑按钮时填充内容
        function get_rowText(button) {
                reminder_remove();
                refullText()

                const rowId = button.getAttribute('data-row-id');
                const row = document.getElementById(rowId);
                const name = row.querySelector('td:nth-child(1)').textContent;
                const description = row.querySelector('td:nth-child(2)').textContent;
                const id = row.querySelector('td:nth-child(3)').textContent;

                // 将后端数据嵌入到 JavaScript 中
                const data = {{ rg_saltname|safe }};  // `data` 是从视图传递到模板的字典
                const rg_acl_data = {{ rg_acl|safe }};  // `rg_acl_data` 是从视图传递到模板的字典

                // 调用 populateSelectedOptions 函数来填充 selectedOptions
                populateSelectedOptions(data, id);

                // 填充acl复选框内容
                const checkboxValues = rg_acl_data[id] || 0;
                // 填充 aclCheck 复选框元素
                if (checkboxValues === 0) {
                    document.getElementById('aclCheck').checked=false;
                    } else {
                    document.getElementById('aclCheck').checked=true;
                    }

                document.querySelector('#input1').value=name;
                document.querySelector('#input2').value=description;

                document.querySelector('#input6').value=id;

                // 显示确认框
                $('#rgModal').modal('show');
            };

        // 添加时清空内容
        function clear_rowText() {
                reminder_remove();

                document.querySelector('#input1').value="";
                document.querySelector('#input2').value="";
                document.querySelector('#input6').value="";
                document.querySelector('#aclCheck').checked=false;
                refullText()
                const initSelectedOptions = document.getElementById('selectedOptions');
                initSelectedOptions.innerHTML = '';  // 清空选项

                // 显示确认框
                $('#rgModal').modal('show');
            };

        //删除resource group
        function del_resource_group() {
            reminder_remove()
            var reminder_msg = document.getElementById("confirm_msg");
            $.ajax({
                type: "post",
                url: "/del_resource_group/",
                dataType: "json",
                data: {
                    rg_id: document.querySelector('#confirmButton').getAttribute('data-id'),
                },
                complete: function () {
                },
                success: function (data) {
                    if (data.status === 0) {
                        reminder_msg.innerHTML = 'Reminder: ' + data.msg;
                        $('#confirmModal').modal('hide');
                        location.reload();
                    } else {

                        reminder_msg.innerHTML = 'Reminder: ' + data.msg;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reminder_msg.innerHTML = 'Reminder: ' + errorThrown;
                }
            });
        }
    </script>
{% endblock %}